import { defineStore } from 'pinia';
import {
  Config,
  Datasource,
  Mapper,
  Output,
  Project,
  Template,
} from 'src/types';
import { ref, Ref, watch } from 'vue';
import { getDocDirname, pathJoin } from 'src/api/SysApi';
import { getFile, saveFile } from 'src/api/FileApi';
import { useConfigStore }    from 'stores/configStore';
import yaml                  from 'js-yaml';

export const useProjectStore = defineStore('project', () => {
  const getSysProjectPath = () => {
    console.log(
      pathJoin(
        getDocDirname(),
        'Qianl Gen',
        'project',
        useConfigStore().config.projectName + '.yml'
      )
    );
    return pathJoin(
      getDocDirname(),
      'Qianl Gen',
      'project',
      useConfigStore().config.projectName + '.yml'
    );
  };
  const project: Ref<Project> = ref({
    // 项目名
    name: useConfigStore().config.projectName, // 生成配置
    out: {
      // 路径
      path: '路径', // 父级
      parent: '父级', // 作者
      author: '作者',
      define: 1, // 生成表
      tables: [] as string[],
    } as Output, // 数据源配置
    datasource: [] as Datasource[], // 映射配置
    mapper: [] as Mapper[], // 模板配置
    template: [] as Template[], // 选择项目
    selected: true,
  } as Project);
  watch(project, async () => {
    await save(project.value);
  },{deep:true});
  const getProject = async (): Promise<unknown> => {
    return new Promise(async (resolve) => {
      const sysProjectData = await getFile(getSysProjectPath(), true);
      if (!sysProjectData) {
        await save({
          // 项目名
          name: useConfigStore().config.projectName, // 生成配置
          out: {
            // 路径
            path: '路径', // 父级
            parent: '父级', // 作者
            author: '作者',
            define: 1, // 生成表
            tables: [] as string[],
          } as Output, // 数据源配置
          datasource: [] as Datasource[], // 映射配置
          mapper: [] as Mapper[], // 模板配置
          template: [] as Template[], // 选择项目
          selected: true,
        } as Project);
        resolve(project.value);
      } else {
        project.value = yaml.load(sysProjectData) as Project;
        resolve(project.value);
      }
    });
  };
  const save = async (data: Project) => {
    project.value = data
    return new Promise((resolve) => {
      saveFile(getSysProjectPath(), yaml.dump(data)).then((r: string) => {
        resolve(r);
      });
    });
  };
  return {
    save,
    getProject,
    project,
  };
});
